<?php

namespace App\Services;

use App\Http\Resources\Home\OrderResource\CreateOrderAfterCollection;
use App\Models\Address;
use App\Models\Cart;
use App\Models\ChangeLog;
use App\Models\CouponLog;
use App\Models\ElectricCollector;
use App\Models\ElectricCommunity;
use App\Models\ElectricElectricity;
use App\Models\ElectricTimeData;
use App\Models\Freight;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\OrderPay;
use App\Models\Store;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ElectricMeterService extends BaseService
{

    use HelperTrait;

    public function get_list()
    {
        $electricity_model = new ElectricElectricity();
        if (!empty(request()->tableAddress)) {
            $electricity_model = $electricity_model->where('tableAddress', 'like', '%' . request()->tableAddress . '%');
        }
        if (request()->code != '') {
            $electricity_model = $electricity_model->where('code', 'like', '%' . request()->code . '%');
        }
        if (request()->plan_id != '') {
            $electricity_model = $electricity_model->where('plan_id', 'like', '%' . request()->plan_id . '%');
        }
        if (request()->charge_id != '') {
            $electricity_model = $electricity_model->where('charge_id', 'like', '%' . request()->charge_id . '%');
        }
        if (request()->collector_id != '') {
            $electricity_model = $electricity_model->where('collector_id', 'like', '%' . request()->collector_id . '%');
        }
        // 下单时间
        $created_at = request()->created_at;
        if (!empty($created_at)) {
            $electricity_model = $electricity_model->whereBetween('created_at', [$created_at[0], $created_at[1]]);
        }
        $electricity_model = $electricity_model->orderBy('id', 'desc')->paginate($request->per_page ?? 30);

        return $this->format($electricity_model);

    }

    /**
     * 2021/3/16--11:18
     * @effect:添加电表设备操作
     * @param $request
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:add
     */
    public function add($request)
    {
        $community_id = "";
        $meter_model = new ElectricElectricity();
        $meter_model->name = $request->name ?? '';//电表名称
        $meter_model->code = $request->code ?? '';//电表资产编号
        $meter_model->tableAddress = $request->tableAddress ?? '';//电表
        $meter_model->number = $request->number ?? '';//初始值
        $meter_model->mult = $request->mult ?? '';//倍率
        $meter_model->collect_id = $request->collect_id ?? '';//设备层级
        $meter_model->level = $request->level ?? '';//设备层级
        $meter_model->community = $community_id ?? '';//区域
        $meter_model->level = $request->level ?? '';//设备层级
        $meter_model->alarm_id = $request->alarm_id ?? '';//报警计划
        $meter_model->charge_id = $request->charge_id ?? '';//缴费计划
        $meter_model->electric_id = $request->electric_id ?? '';//父级电表
        $meter_model->brand = $request->brand ?? '';//品牌
        $meter_model->cate = $request->cate ?? '';//接入象限

        try {
            $meter_model->save();
            return $this->format($meter_model->id, '添加电表成功');
        } catch (\Exception $e) {
            return $this->format_error('数据模型操作错误：' . $e->getMessage());
        }
    }

    /**
     * 2021/3/16--11:18
     * @effect:添加电表设备操作
     * @param $request
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:edit
     */
    public function edit($request): ?array
    {

        $community_id = '';
        $meter_model = new ElectricElectricity();
        $meter_model = $meter_model->find($request->id);
        $meter_model->name = $request->name ?? '';//电表名称
        $meter_model->code = $request->code ?? '';//电表资产编号
        $meter_model->tableAddress = $request->tableAddress ?? '';//电表
        $meter_model->number = $request->number ?? '';//初始值
        $meter_model->mult = $request->mult ?? '';//倍率
        $meter_model->collect_id = $request->collect_id ?? '';//设备层级
        $meter_model->level = $request->level ?? '';//设备层级
        $meter_model->community = $community_id ?? '';//区域
        $meter_model->level = $request->level ?? '';//设备层级
        $meter_model->alarm_id = $request->alarm_id ?? '';//报警计划
        $meter_model->charge_id = $request->charge_id ?? '';//缴费计划
        $meter_model->electric_id = $request->electric_id ?? '';//父级电表
        $meter_model->brand = $request->brand ?? '';//品牌
        $meter_model->cate = $request->cate ?? '';//接入象限

        try {
            $meter_model->save();
            return $this->format($meter_model->id, '编辑电表成功');
        } catch (\Exception $e) {
            return $this->format_error('数据模型操作错误：' . $e->getMessage());
        }
    }

    /**
     * @Notes 获取详情
     * @param $id
     * @return array
     * @author ypp
     * @date 2021/3/18
     * @time 16:11
     */
    public function getElectricDetail($id)
    {
        $data = ElectricElectricity::query()
            ->with('one_collector')
            ->with('one_plan')
            ->with('one_alarm')
            ->with('parent_code')
            ->where(['id'=>$id])->first();
        switch ($data->brand){
            case 1:
                $data->brand = '国网';
                break;
            case 2:
                $data->brand = '雷甸';
                break;
            default:
                $data->brand = '';
        }
        return $this->format($data);
    }


    public function getTimeData($id,$communityId,$tableAddress,$code)
    {
        $table = 'electric_electricity_data' . $communityId;
        //先查询实时数据表15分钟到当前时间是否有数据
        $before_data = date('Y-m-d H:i:s', strtotime('-15 minute'));
        $real_data = ElectricTimeData::query()
            ->where(['meter_code' => $tableAddress])
            ->whereBetween('update_time', [$before_data, date('Y-m-d H:i:s')])
            ->first();
        $new_data = [];
        if (!$real_data) //如果实时数据表没有数据就查询data表最新的数据
        {
            $devTime = DB::connection("mysql_center")->table($table)
                ->where(['electricity_code' => $tableAddress, 'object_name' => 'electricity'])
                ->orderBy('create_time','desc')
                ->value('devTime');
            $new_data_ = Db::connection("mysql_center")->table($table)
                ->where(['electricity_code' => $tableAddress, 'devTime' => $devTime])
                ->orderBy('create_time','desc')
                ->get()->toArray();
            foreach ($new_data_ as $k => $v) {
                $new_data[$v->object_name] = $v->object_val;
                $new_data['devTime']=$devTime;
            }
        } else {
            $new_data = json_decode($real_data['obj_val'], 1);
        }
        if(!isset($new_data['devTime'])){
            $new_data['devTime'] = $new_data['Utc'];
        }
        $is_date = strtotime($new_data['devTime']) ? strtotime($new_data['devTime']) : false;
        if ($is_date === false) {
            $new_data['devTime'] = date('Y-m-d H:i:s',$new_data['devTime']);
        }else{
            $new_data['devTime'] = date('Y-m-d H:i:s',strtotime($new_data['devTime']));
        }

        //查询余额
        $balance = DB::connection("mysql_center")->table('electric_platform_owner')
            ->select('id','elc_code','electricity_bill_balance')->where(['elc_code' => $code])->first();
        $new_data['userInfo'] = $balance;
        //查询电报数据
        $eleData = $ele = DB::connection("mysql_center")->table('electric_electricity')->select('id','name','is_protect','is_close','cate','code','collect_id')->find($id);
        switch ($eleData->is_protect){
            case 1:
                $eleData->protect = '是';
                break;
            case 2:
                $eleData->protect = '否';
                break;
        }
        switch ($eleData->is_close){
            case 1:
                $eleData->close = '未拉闸';
                break;
            case 2:
                $eleData->close = '拉闸';
                break;
        }
        $new_data['eleData'] = $eleData;
        return $this->format($new_data);
    }

    /**
     * @Notes  获取数据报表的数据
     * @return array
     * @author ypp
     * @date 2021/3/19
     * @time 11:18
     */
    public function getDataReport()
    {
        $type = request()->type;
        $cate = request()->cate;
        $create_time = request()->create_time;
        $code = request()->code;
        $community = request()->community;
        $table = 'electric_electricity_data' . $community;
        switch ($type) {
            case 1:  //按天查询
                if (empty($create_time)) //按天查询时如果不传时间，默认查当前日期的数据
                    $create_time = date('Y-m-d', time());
                //DB::connection()->enableQueryLog();
                $data = DB::connection("mysql_center")->table($table)
                    ->where(['day_time' => $create_time, 'object_name' => $cate, 'electricity_code' => $code])
                    ->get()->toArray();
               // dump(DB::getQueryLog());
                $dateArr = [];
                foreach ($data as $k => $v) {
                    $timeStr = '';
                    $is_date = strtotime($v->devTime) ? strtotime($v->devTime) : false;
                    if ($is_date === false) {
                        if (!empty($v->devTime)) {
                            $timeStr = date('Y-m-d H:i', $v->devTime);
                        } else {
                            unset($data[$k]);
                        }
                    } else {
                        $timeStr = date('Y-m-d H:i', strtotime($v->devTime));
                    }
                    $dateArr[] = ['time'=>$timeStr,'num'=>$v->object_val];
                }
                return $this->format($dateArr);
                break;

            case 2:
                $time_e = date('Y-m-d', time());
                $dateArr = [];

                for ($i = 0; $i < 30; $i++) {
                    $xdate[] = date('Y-m-d', strtotime("-$i day", strtotime($time_e)));
                    $date['time'] = date('Y-m-d', strtotime("-$i day", strtotime($time_e)));
                    $date['num'] = 0;
                    $dateArr[] = $date;
                }
                $dates = array_column($dateArr, 'time');
                $data = DB::connection("mysql_center")->table($table)
                    ->whereIn('day_time', $dates)
                    ->where(['object_name' => $cate, 'electricity_code' => $code])
                    ->get();

                foreach ($dateArr as $k => $v) {
                    $count = $v['num'];
                    foreach ($data as $k1 => $v1) {
                        if ($v['time'] == $v1->day_time) {
                            $is_date = strtotime($v1->devTime) ? strtotime($v1->devTime) : false;
                            if ($is_date === false) {
                                $dateArr[$k]['time'] = date('Y-m-d H:i', $v1->devTime);
                            } else {
                                $dateArr[$k]['time'] = date('Y-m-d H:i', strtotime($v1->devTime));
                            }

                            if ($count < $v1->object_val) {
                                $count = $v1->object_val;
                            }
                        }
                        $dateArr[$k]['num'] = $count;
                    }
                }
                return $this->format($dateArr);
                break;
        }
    }

    /**
     * @Notes  获取数据报表的数据
     * @return array
     * @author ypp
     * @date 2021/3/19
     * @time 11:18
     */
    public function getElectricReport()
    {
        $type = request()->type;
        $create_time = request()->create_time;
        $code = request()->code;
        $year = request()->year ? request()->year : date('Y', time());
        switch ($type) {
            case 1:  //按月
                if (empty($create_time)) //如果不传时间就默认当月
                    $create_time = date('Y-m', time());
                $timeArr = explode('-', $create_time);
                $data = DB::connection("mysql_center")->table('electric_meter_reading_log')
                    ->select('tableAddress','day_time',DB::raw('SUM(day_count) as day_count'))
                    ->where(['year' => $timeArr[0], 'month' => $timeArr[1], 'tableAddress' => $code])
                    ->groupBy('day_time')
                    ->get();
                $days = date('t', strtotime($create_time));
                $dateArr = [];
                for ($i = 0; $i < $days; $i++) {
                    $xdate[] = date('Ymd', strtotime("+$i days", strtotime($create_time)));
                    $date['time'] = date('Y-m-d', strtotime("+$i days", strtotime($create_time)));
                    $date['num'] = 0;
                    $dateArr[] = $date;

                }
                foreach ($dateArr as $k => $v) {
                    foreach ($data as $k1 => $v1) {
                        if (strtotime($v['time']) == $v1->day_time) {
                            $dateArr[$k]['num'] = $v1->day_count;
                        }
                    }
                }
                return $this->format($dateArr);
                break;

            case 2:
                $month_s = $year . '-01';
                for ($i = 0; $i < 12; $i++) {
                    $xdate[] = date('m', strtotime("+$i month", strtotime($month_s)));
                    $date['time'] = date('m', strtotime("+$i month", strtotime($month_s)));
                    $date['num'] = 0;
                    $dateArr[] = $date;
                }
                $data = DB::connection("mysql_center")->table('electric_meter_reading_log')
                    ->select('tableAddress','month','year',DB::raw('SUM(day_count) as day_count'))
                    ->where(['year' => $year, 'tableAddress' => $code])
                    ->whereIn('month', $xdate)
                    ->groupBy('month')
                    ->get();
                foreach ($dateArr as $k => $v) {
                    foreach ($data as $k1 => $v1) {
                        if ($v['time'] == $v1->month) {
                            $dateArr[$k]['num'] = $v1->day_count;
                        }
                    }
                }
                return $this->format($dateArr);
                break;
        }
    }

    /**
     * @Notes 获取实时数据
     * @return array
     * @author ypp
     * @date 2021/3/19
     * @time 18:30
     */
    public function getRealTimeData()
    {
        $code = request()->tableAddress;
        $collect_id = request()->collect_id;
        $collect_code = DB::connection("mysql_center")
            ->table('electric_collector')
            ->where(['id' => $collect_id])
            ->value('code');
        $arr = ['electric_code' => $code, 'device_type' => 1, 'collect_id' => $collect_code];
        $result = Artisan::call('real_time_data', $arr);
        sleep(4);//等待命令执行时间
        $count = DB::connection("mysql_center")
            ->table('electric_electricity')
            ->where(['collect_id' => $collect_id, 'is_report' => 1])
            ->count();
        if ($count > 0) {
            return $this->format_error('尚有设备未添加入网关，请到采集器处上报');
        }
        if ($result == 0) {
            return $this->format([]);
        } else {
            return $this->format_error('系统故障');
        }
    }

    public function changeLog(){
        $old = request()->old_code;
        $new = request()->new_code;
        $model = new ChangeLog();
        if($old){
            $model = $model->where('old_code', 'like', '%'.$old.'%');
        }
        if($new){
            $model = $model->where('new_code', 'like', '%'.$new.'%');
        }
        return $model -> orderBy('id','desc')->select() -> paginate(15) -> toArray();
    }

}
